// 用户角色
export enum UserRole {
  ADMIN = "admin",
  USER = "user",
  MODERATOR = "moderator",
}

// 权限类型
export enum Permission {
  // 用户管理权限
  USER_VIEW = "user:view",
  USER_CREATE = "user:create",
  USER_UPDATE = "user:update",
  USER_DELETE = "user:delete",

  // 内容管理权限
  CONTENT_VIEW = "content:view",
  CONTENT_CREATE = "content:create",
  CONTENT_UPDATE = "content:update",
  CONTENT_DELETE = "content:delete",
  CONTENT_MODERATE = "content:moderate",

  // 系统管理权限
  SYSTEM_VIEW = "system:view",
  SYSTEM_CONFIG = "system:config",
  SYSTEM_LOG = "system:log",

  // 安全权限
  SECURITY_VIEW = "security:view",
  SECURITY_CONFIG = "security:config",
}

// 角色权限映射
const rolePermissions: Record<UserRole, Permission[]> = {
  [UserRole.ADMIN]: [
    Permission.USER_VIEW,
    Permission.USER_CREATE,
    Permission.USER_UPDATE,
    Permission.USER_DELETE,
    Permission.CONTENT_VIEW,
    Permission.CONTENT_CREATE,
    Permission.CONTENT_UPDATE,
    Permission.CONTENT_DELETE,
    Permission.CONTENT_MODERATE,
    Permission.SYSTEM_VIEW,
    Permission.SYSTEM_CONFIG,
    Permission.SYSTEM_LOG,
    Permission.SECURITY_VIEW,
    Permission.SECURITY_CONFIG,
  ],
  [UserRole.MODERATOR]: [
    Permission.USER_VIEW,
    Permission.CONTENT_VIEW,
    Permission.CONTENT_UPDATE,
    Permission.CONTENT_MODERATE,
    Permission.SYSTEM_VIEW,
    Permission.SYSTEM_LOG,
  ],
  [UserRole.USER]: [Permission.CONTENT_VIEW, Permission.CONTENT_CREATE],
};

// 用户信息接口
export interface AuthUser {
  id: string;
  username: string;
  email: string;
  role: UserRole;
  permissions: Permission[];
  isActive: boolean;
  lastLoginTime?: string;
}

// 权限管理器
class AuthManager {
  private currentUser: AuthUser | null = null;
  private token: string | null = null;

  // 设置当前用户
  setCurrentUser(user: AuthUser): void {
    this.currentUser = user;
    // 存储到localStorage
    localStorage.setItem("admin_user", JSON.stringify(user));
  }

  // 获取当前用户
  getCurrentUser(): AuthUser | null {
    if (!this.currentUser) {
      const stored = localStorage.getItem("admin_user");
      if (stored) {
        this.currentUser = JSON.parse(stored);
      }
    }
    return this.currentUser;
  }

  // 设置token
  setToken(token: string): void {
    this.token = token;
    localStorage.setItem("admin_token", token);
  }

  // 获取token
  getToken(): string | null {
    if (!this.token) {
      this.token = localStorage.getItem("admin_token");
    }
    return this.token;
  }

  // 检查是否有权限
  hasPermission(permission: Permission): boolean {
    const user = this.getCurrentUser();
    if (!user || !user.isActive) {
      return false;
    }

    // 管理员拥有所有权限
    if (user.role === UserRole.ADMIN) {
      return true;
    }

    return user.permissions.includes(permission);
  }

  // 检查是否有任意一个权限
  hasAnyPermission(permissions: Permission[]): boolean {
    return permissions.some((permission) => this.hasPermission(permission));
  }

  // 检查是否有所有权限
  hasAllPermissions(permissions: Permission[]): boolean {
    return permissions.every((permission) => this.hasPermission(permission));
  }

  // 检查角色
  hasRole(role: UserRole): boolean {
    const user = this.getCurrentUser();
    return user?.role === role;
  }

  // 检查是否有任意一个角色
  hasAnyRole(roles: UserRole[]): boolean {
    const user = this.getCurrentUser();
    return roles.includes(user?.role || UserRole.USER);
  }

  // 获取用户权限
  getUserPermissions(): Permission[] {
    const user = this.getCurrentUser();
    return user?.permissions || [];
  }

  // 获取用户角色
  getUserRole(): UserRole | null {
    const user = this.getCurrentUser();
    return user?.role || null;
  }

  // 检查是否已登录
  isAuthenticated(): boolean {
    return !!this.getCurrentUser() && !!this.getToken();
  }

  // 检查是否是管理员
  isAdmin(): boolean {
    return this.hasRole(UserRole.ADMIN);
  }

  // 登出
  logout(): void {
    this.currentUser = null;
    this.token = null;
    localStorage.removeItem("admin_user");
    localStorage.removeItem("admin_token");
  }

  // 生成用户权限（根据角色）
  generateUserPermissions(role: UserRole): Permission[] {
    return rolePermissions[role] || [];
  }
}

// 创建全局权限管理器实例
export const authManager = new AuthManager();

// 权限指令
export const permissionDirective = {
  mounted(el: HTMLElement, binding: any) {
    const { value } = binding;

    if (value) {
      const permissions = Array.isArray(value) ? value : [value];
      const hasPermission = authManager.hasAnyPermission(permissions);

      if (!hasPermission) {
        el.style.display = "none";
      }
    }
  },
};

// 角色指令
export const roleDirective = {
  mounted(el: HTMLElement, binding: any) {
    const { value } = binding;

    if (value) {
      const roles = Array.isArray(value) ? value : [value];
      const hasRole = authManager.hasAnyRole(roles);

      if (!hasRole) {
        el.style.display = "none";
      }
    }
  },
};

// 路由守卫
export const createRouteGuard = () => {
  return {
    // 前置守卫
    beforeEach: (to: any, from: any, next: any) => {
      // 检查是否需要认证
      if (to.meta.requiresAuth && !authManager.isAuthenticated()) {
        next("/admin/login");
        return;
      }

      // 检查权限
      if (to.meta.permissions) {
        const permissions = Array.isArray(to.meta.permissions) ? to.meta.permissions : [to.meta.permissions];

        if (!authManager.hasAnyPermission(permissions)) {
          next("/admin/403");
          return;
        }
      }

      // 检查角色
      if (to.meta.roles) {
        const roles = Array.isArray(to.meta.roles) ? to.meta.roles : [to.meta.roles];

        if (!authManager.hasAnyRole(roles)) {
          next("/admin/403");
          return;
        }
      }

      next();
    },
  };
};
